package com.lanou.tipsy.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.lanou.tipsy.MusicIdle;
import com.lanou.tipsy.R;
import com.lanou.tipsy.activity.PlayerActivity;
import com.lanou.tipsy.base.BaseApplication;
import com.lanou.tipsy.base.Constants;
import com.lanou.tipsy.broadcastReceiver.NotificationRecevier;
import com.lanou.tipsy.data.MyEventBus;
import com.lanou.tipsy.entity.playerList.personal.PersonalList;
import com.lanou.tipsy.entity.songInfo.SongInfoRoot;
import com.lanou.tipsy.tools.findLocalSongs.FindSongs;
import com.lanou.tipsy.tools.lrc.LyricDownloadManager;
import com.lanou.tipsy.tools.lrc.LyricLoadHelper;
import com.lanou.tipsy.tools.myConfig.MyConfig;
import com.lanou.tipsy.tools.volley.ResponseErrorListener;
import com.lanou.tipsy.tools.volley.VolleySingleton;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import de.greenrobot.event.EventBus;

/**
 * Created by FengJun on 0.
 * 服务类
 */
public class MyService extends Service {
    public static final String TAG = "MyService";
    private MediaPlayer mediaPlayer;
    private int index = -1;//定义当前正在播放的歌曲的位置
    private boolean isplay = false;
    private String songTitle;//歌曲名字
    private String singerName;//歌手名字
    private String pictureUrl;//网络歌曲图片的url
    private Bitmap imageUri;//本地歌曲图片的uri
    private String tag;//用于分辨本地歌曲和网络歌曲
    //定义一个handler用于刷新进度
    private Handler handler = new Handler();
    //我的歌曲列表
    private List<PersonalList> personalLists;
    private PersonalList personalList;
    private String modeFlag;//播放模式
    private boolean flag = true;

    private VolleySingleton volleySingleton;
    private StringRequest request;
    private ResponseErrorListener errorListener;
    private SongInfoRoot root;//网络歌曲url实体类
    private LyricDownloadManager lyricDownloadManager;
    private LyricLoadHelper mLyricLoadHelper;//下载歌词helper类
    private boolean mIsLyricDownloading;//歌词是否正在下载
    private NotificationManager manager;
    private RemoteViews remoteViews;
    private NotificationCompat.Builder builder;

    //获得正在播放的歌曲列表信息
    public void onEvent(MyEventBus.NetSongs netSongs) {
        try {
            if (mediaPlayer.isPlaying()) {
                handler.removeCallbacks(runnable);
                mBindle.stop();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        personalLists = netSongs.getPersonalLists();
        this.index = netSongs.getPosition();
        tag = personalLists.get(index).getTag();
        Log.i("test", TAG + "->tag:" + tag);
        getSongInfo(tag, index);
        EventBus.getDefault().post(new MyEventBus.SetSongInfo(singerName, songTitle, tag));
        //发送数据到Activity--->歌曲信息
        EventBus.getDefault().post(new MyEventBus.PersonalLists((ArrayList<PersonalList>) personalLists));
    }

    private void getSongInfo(String tag, int index) {
        Log.i("test", TAG + "->getSongInfo->tag:" + tag + ",index:" + index);
        if (tag.equals("网络歌曲")) {
            final String url = Constants.SERVICE_NET_SONGS_URL_START + personalLists.get(index).getSongsUrl() + Constants.SERVICE_NET_SONGS_URL_END;
            request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("test", "------>>>" + url);
                    root = JSON.parseObject(response, SongInfoRoot.class);
                    String songUrl = root.getSongurl().getUrl().get(0).getFile_link();
                    String lrcUrl = root.getSonginfo().getLrclink();
                    Log.i("test", TAG + "->歌曲url:" + songUrl);
                    Log.i("test", TAG + "->LRC.lrc:" + lrcUrl);
                    try {
                        mBindle.setUrl(songUrl, lrcUrl);
                        loadLyricByHand(root.getSonginfo().getTitle(), lrcUrl);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    songTitle = root.getSonginfo().getTitle();
                    singerName = root.getSonginfo().getAuthor();
                    pictureUrl = root.getSonginfo().getPic_big();
                    EventBus.getDefault().post(new MyEventBus.SetNetPitcure(pictureUrl));
                }
            }, errorListener);
            volleySingleton.addQueue(request, "netSongs");
        } else if (tag.equals("本地歌曲")) {
            String url = personalLists.get(index).getSongsUrl();
            try {
                mBindle.setUrl(url, "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            songTitle = personalLists.get(index).getSongTitle();
            singerName = personalLists.get(index).getSingerName();
            imageUri = FindSongs.getArtwork(MyService.this, personalLists.get(index).getId(),
                    personalLists.get(index).getAlbum_id(), true, true);
            EventBus.getDefault().post(new MyEventBus.SetLocalPicture(imageUri));
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBindle;
    }

    //定义一个handler用于刷新进度条
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isplay) {
                handler.postDelayed(runnable, 500);
                if (mediaPlayer != null) {
                    //实时发送进度条信息,正在播放的歌曲信息,正在播放的歌曲列表
                    EventBus.getDefault().post(new MyEventBus.CurrentProgress(mediaPlayer.getCurrentPosition()));
                    EventBus.getDefault().post(new MyEventBus.MaxProgress(mediaPlayer.getDuration()));
                    if (tag != null && tag.equals("本地歌曲")) {
                        EventBus.getDefault().post(new MyEventBus.SetLocalPicture(imageUri));
                    } else if (tag != null && tag.equals("网络歌曲")) {
                        EventBus.getDefault().post(new MyEventBus.SetNetPitcure(pictureUrl));
                    }
                    if (singerName != null && songTitle != null && tag != null) {
                        EventBus.getDefault().post(new MyEventBus.SetSongInfo(singerName, songTitle, tag));
                    }
                    EventBus.getDefault().post(new MyEventBus.PersonalLists((ArrayList<PersonalList>) personalLists));
                    EventBus.getDefault().post(new MyEventBus.ListPosition(index));
                }
            }
        }
    };


    //获得当前选择的播放模式
    public void onEvent(MyEventBus.CurrentMode mode) {
        this.modeFlag = mode.getMode();
        Log.i("test", TAG + "->当前播放模式为:" + modeFlag);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("test", TAG + "->onCreate");
        lyricDownloadManager = new LyricDownloadManager();
        mLyricLoadHelper = new LyricLoadHelper();
        EventBus.getDefault().register(this);
        volleySingleton = VolleySingleton.getInstance();
        errorListener = new ResponseErrorListener();
        personalLists = new ArrayList<>();//我的歌曲列表
        initMediaPlayer();
        modeFlag = MyConfig.getSharePreStr(MyService.this, "playingMode", "currentMode");
        //播放准备的监听
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                try {
                    Log.d("test", TAG + "->准备好了,开始播放");
                    mBindle.play();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        //歌曲播放完成的监听
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                try {
                    mBindle.next();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    //初始化mediaPlayer
    public MediaPlayer initMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            return mediaPlayer;
        } else {
            return mediaPlayer;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.release();
        mediaPlayer = null;
        EventBus.getDefault().unregister(this);
    }

    //实现aidl接口
    MusicIdle.Stub mBindle = new MusicIdle.Stub() {

        //下一曲
        @Override
        public void next() throws RemoteException {
            Log.i("test", TAG + "aidl---next");
            if (personalLists.size() > 0 && flag) {
                switch (modeFlag) {
                    case "looping":
                        if (index + 1 > personalLists.size() - 1) {
                            Log.i("test", TAG + "index" + index);
                            index = 0;
                        } else {
                            index++;
                        }
                        break;
                    case "single":
                        break;
                    case "random":
                        index = new Random().nextInt(personalLists.size());
                        break;
                    case "sequence":
                        if (index + 1 > personalLists.size() - 1) {
                            isplay = false;
                            mediaPlayer.stop();
                            //mediaPlayer = null;
                            Toast.makeText(MyService.this, "所有歌曲播放完毕", Toast.LENGTH_SHORT).show();
                            Log.i("test", TAG + "->index的值:" + index);
                        } else {
                            index++;
                        }
                        break;
                    default:
                        if (index + 1 > personalLists.size() - 1) {
                            Log.i("test", TAG + "index" + index);
                            index = 0;
                        } else {
                            index++;
                        }
                        break;
                }
                Log.i("test", TAG + "->播放模式" + modeFlag);
                EventBus.getDefault().post(new MyEventBus.ListPosition(index));
                getSongInfo(tag, index);
                EventBus.getDefault().post(new MyEventBus.SetSongInfo(singerName, songTitle, tag));
            } else {
                flag = true;
            }

            showView(songTitle, singerName);
        }

        //上一曲
        @Override
        public void previous() throws RemoteException {
            Log.i("test", TAG + "->aidl---previous");
            if (personalLists.size() > 0) {
                if (index == 0) {
                    index = personalLists.size() - 1;
                } else {
                    index--;
                }
                EventBus.getDefault().post(new MyEventBus.ListPosition(index));
                getSongInfo(tag, index);
                EventBus.getDefault().post(new MyEventBus.SetSongInfo(singerName, songTitle, tag));
            }

        }

        //播放
        @Override
        public void play() throws RemoteException {
            Log.i("test", TAG + "->aidl->play");
            try {
                handler.removeCallbacks(runnable);
            } catch (Exception e) {

            }
            mediaPlayer.start();
            isplay = true;
            handler.postDelayed(runnable, 500);//发送handler
            showView(songTitle, singerName);
        }

        //暂停
        @Override
        public void pause() throws RemoteException {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
            Log.i("test", TAG + "->aidl->pause");

        }

        //停止
        @Override
        public void stop() throws RemoteException {
            Log.i("test", TAG + "->aidl->stop");
            mediaPlayer.stop();
        }

        //是否正在播放
        @Override
        public boolean isPlaying() throws RemoteException {
            Log.i("test", TAG + "->aidl->isPlaying");
            return mediaPlayer.isPlaying();
        }

        //设置网址->设置
        @Override
        public void setUrl(String url, String lrcUrl) throws RemoteException {
            try {
                handler.removeCallbacks(runnable);
                mediaPlayer.reset();
                mediaPlayer.setDataSource(url);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置音频流
                mediaPlayer.prepareAsync();
                Log.i("test", TAG + "->aidl->setUrl->success");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //得到当前进度
        @Override
        public int getCurrentProgress() throws RemoteException {
            Log.d("test", TAG + "->getCurrentProgress");
            return mediaPlayer.getCurrentPosition();
        }

        //得到最大进度
        @Override
        public int getDuration() throws RemoteException {
            Log.d("test", TAG + "->getMaxProgress");
            return mediaPlayer.getDuration();
        }

        //刷新进度条
        @Override
        public void setSeekTo(int progress) throws RemoteException {
            Log.d("test", TAG + "->seekTo");
            mediaPlayer.seekTo(progress);
        }

        @Override
        public void setIndex(int index) throws RemoteException {
            MyService.this.index = index;
        }

    };

    private void loadLyricByHand(String musicName, String lrcUrl) {
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = BaseApplication.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {
            mIsLyricDownloading = true;
            // 尝试网络获取歌词
            new LyricDownloadAsyncTask().execute(musicName, lrcUrl);

        }
    }

    //下载歌词异步任务
    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            String lyricFilePath = lyricDownloadManager.fetchLyricContent(
                    params[1], params[0]);
            // 返回本地歌词路径
            mIsLyricDownloading = false;
            return lyricFilePath;
        }

        @Override
        protected void onPostExecute(String result) {
            // Log.i(TAG, "网络获取歌词完毕，歌词保存路径:" + result);
            // 读取保存到本地的歌曲
            mLyricLoadHelper.loadLyric(result);
        }
    }

    private void showView(String songName, String singerName) {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        remoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_button);

        remoteViews.setTextViewText(R.id.tv_custom_song_name, songName);
        remoteViews.setTextViewText(R.id.tv_custom_song_singer, singerName);
        // 设置按钮事件 -- 发送广播 --广播接收后进行对应的处理

//        Intent buttonPlayIntent = new Intent(
//                NotificationRecevier.NOTIFICATION_ITEM_BUTTON_LAST); // ----设置通知栏按钮广播
//        PendingIntent pendButtonPlayIntent = PendingIntent.getBroadcast(this,
//                0, buttonPlayIntent, 0);
//        remoteViews.setOnClickPendingIntent(R.id.last_music,
//                pendButtonPlayIntent);// ----设置对应的按钮ID监控

        Intent buttonPlayIntent1 = new Intent(
                NotificationRecevier.NOTIFICATION_ITEM_BUTTON_PLAY); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent1 = PendingIntent.getBroadcast(MyService.this,
                0, buttonPlayIntent1, 0);
        remoteViews.setOnClickPendingIntent(R.id.btn_custom_play,
                pendButtonPlayIntent1);// ----设置对应的按钮ID监控

        Intent buttonPlayIntent2 = new Intent(
                NotificationRecevier.NOTIFICATION_ITEM_BUTTON_NEXT); // ----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent2 = PendingIntent.getBroadcast(MyService.this,
                0, buttonPlayIntent2, 0);
        remoteViews.setOnClickPendingIntent(R.id.btn_custom_next,
                pendButtonPlayIntent2);// ----设置对应的按钮ID监控

        Intent buttonDeleteIntent = new Intent(
                NotificationRecevier.NOTIFICATION_ITEM_BUTTON_DELETE); // ----设置通知栏清除按钮
        PendingIntent pendButtonDeleteIntent = PendingIntent.getBroadcast(MyService.this,
                0, buttonDeleteIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.bt_notic_cancel,
                pendButtonDeleteIntent);// ----设置对应的按钮ID监控

        Intent intentToActivity = new Intent(MyService.this, PlayerActivity.class);
        PendingIntent pi = PendingIntent.getActivity(MyService.this, 100, intentToActivity, PendingIntent.FLAG_UPDATE_CURRENT);
        builder = new NotificationCompat.Builder(MyService.this);
        builder.setContent(remoteViews).setSmallIcon(R.mipmap.sing_icon)
                .setOngoing(true).setTicker("正在播放");
        builder.setContentIntent(pi);
        manager.notify(1, builder.build());
    }

    public void onEvent(MyEventBus.Play play) {
        switch (play.getWhat()) {
            case 1:

                try {
                    if (mediaPlayer.isPlaying()) {
                        mBindle.pause();
                    } else
                        mBindle.play();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                break;
            case 2:
                try {
                    mBindle.next();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case 3:
                manager.cancel(1);
                break;
        }
    }

}
